<template>
  <div>
    <el-drawer v-model="_isOpen" size="1000" title="更多筛选" :direction="'rtl'" modal-class="my-drawer">
      <template #header>
        <h4>更多筛选</h4>
      </template>
      <template #default>
        <div class="content">
          <div class="left">
            <el-scrollbar height="100%">
              <ul>
                <li
                  :class="{ active: item.categoryId === selectedLeftObj.categoryId }"
                  v-for="(item, index) in category"
                  :key="item.categoryId"
                  @click="selectedCate1(item)"
                >
                  {{ item.name }}
                </li>
              </ul>
            </el-scrollbar>
          </div>
          <div class="middle">
            <el-scrollbar height="100%">
              <!-- 方案二 -->
              <div v-if="selectedLeftObj.children.length > 0" class="pt10">
                <div v-for="(item, index) in selectedLeftObj.children" :key="item.categoryId">
                  <div class="attr-item">
                    <el-checkbox-group v-model="filterValMid" size="small">
                      <div class="cate-wrap">
                        <el-checkbox
                          :label="item.name"
                          :value="item.categoryId"
                          :key="item.categoryId"
                          @change="
                            val => {
                              changeCate2(val, selectedLeftObj, item);
                            }
                          "
                        >
                          <template #default>
                            <p class="cate2">{{ item.name }}({{ item.warnProductNum || "-" }})</p>
                          </template>
                        </el-checkbox>
                        <div class="cate3 ml4" v-if="item?.children?.length > 0">
                          <el-select
                            v-model="item.select3"
                            placeholder="请选择"
                            size="small"
                            clearable
                            style="min-width: 120px"
                            multiple
                            @change="
                              val => {
                                changeCate3(val, item, index, index2);
                              }
                            "
                          >
                            <el-option
                              v-for="item3 in item.children"
                              :key="item3.categoryId"
                              :label="item3.name"
                              :value="item3.categoryId"
                            />
                          </el-select>
                        </div>
                      </div>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
              <div v-else style="display: flex; justify-content: center; width: 100%">
                <el-empty description="暂无数据" />
              </div>
            </el-scrollbar>
          </div>
          <div class="right">
            <el-scrollbar height="100%">
              <div v-if="_filterData.length > 0">
                <!-- 品牌 -->
                <div class="attr-item mb20">
                  <p style="color: #86909c; font-size: 16px">品牌：</p>
                  <el-checkbox-group v-model="brandIds" size="small">
                    <!-- 二级品牌-->
                    <div
                      v-for="(item2, index2) in _filterData[0]?.brands || []"
                      class="attr-wrap"
                      :class="{ 'attr-only2': item2?.children?.length <= 0 || !item2?.children }"
                      :key="index2"
                    >
                      <el-checkbox :label="item2.bandName" :value="item2.brandId" :key="item2.brandId">
                        <template #default>
                          <p class="attr2">{{ item2.bandName }}</p>
                          <!-- <img
                      class="active-icon"
                      v-if="item2?.children?.length <= 0 || !item2?.children"
                      src="@/assets/images/chose_icon.png"
                      alt=""
                    /> -->
                        </template>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </div>
                <div v-for="(item, index) in _filterData" :key="item.stastsId">
                  <div class="attr-item mb20">
                    <p>{{ item.stastsName }}：</p>
                    <el-checkbox-group v-model="filterVal[index]" size="small">
                      <!-- 二级属性 -->
                      <div v-for="(item2, index2) in item.children" class="attr-wrap" :key="index2">
                        <el-checkbox
                          :label="item2.stastsName"
                          :value="item2.stastsId"
                          :key="item2.stastsId"
                          @change="
                            val => {
                              changeAttr2(val, item, item2, index);
                            }
                          "
                        >
                          <template #default>
                            <p class="attr2">{{ item2.stastsName }}({{ item2.productNum || "-" }})</p>
                          </template>
                        </el-checkbox>
                        <!-- 三级属性 -->
                        <div class="attr3 ml4" v-if="item2?.children?.length > 0">
                          <el-select
                            v-model="item2.select3"
                            placeholder="请选择"
                            size="small"
                            clearable
                            style="min-width: 120px"
                            multiple
                            @change="
                              val => {
                                changeAttr3(val, item, item2, index, index2);
                              }
                            "
                          >
                            <el-option
                              v-for="item3 in item2.children"
                              :key="item3.stastsId"
                              :label="item3.stastsName"
                              :value="item3.stastsId"
                            />
                          </el-select>
                        </div>
                      </div>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
              <div v-else style="display: flex; justify-content: center; width: 100%">
                <el-empty description="暂无数据" />
              </div>
            </el-scrollbar>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">重置</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { getWarnStatsList } from "@/api/products/selection";

const emit = defineEmits(["update:isOpen", "changeAttr"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  category: {
    type: Object,
    default: () => {}
  },
  params: {
    type: Object,
    default: () => {}
  }
});
// ==========middle====================================================================
const _category = ref([]); //筛选的属性值
const _categoryCopy = ref([]); //筛选的属性值
const filterValMid = ref([]); //用户选中的分类id
const filterValMid3 = ref([]); //用户选中的3级筛选属性值
const selectedLeftObj = ref({ children: [] }); //一级分类选中的obj
// ==========right=====================================================================
const _filterData = ref([]); //筛选的属性值
const filterVal = ref([]); //用户选中的筛选属性值
const filterVal3 = ref([]); //用户选中的3级筛选属性值
const brandIds = ref([]);

watch(
  () => props.category,
  val => {
    _category.value = JSON.parse(JSON.stringify(val));
    _categoryCopy.value = JSON.parse(JSON.stringify(val));
  },
  { deep: true }
);
const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

// ==========================================left、middle=============================================================================
const selectedCate1 = obj => {
  resetAll();
  selectedLeftObj.value = JSON.parse(JSON.stringify(obj)); //可以渲染middle数据
  // getAttrListFun(); //获取选中分类对应的属性列表-right数据
};
//2级分类筛选
const changeCate2 = (val, item, item2) => {
  // console.log("这是2级分类筛选===", item.children, filterValMid.value);

  if (!val) {
    item2.select3 = null;
  }
  let ARR = [];
  // for (let attr1 of _category.value) {
  //   for (let attr2 of attr1.children) {
  //     if (attr2.select3 && attr2.select3?.length > 0) {
  //       attr2.select3.map(obj => {
  //         ARR.push(attr2.categoryId + "-" + obj);
  //       });
  //     }
  //   }
  // }
  for (let attr2 of selectedLeftObj.value.children) {
    console.log("ppppp", attr2);
    if (attr2.select3 && attr2.select3?.length > 0) {
      attr2.select3.map(obj => {
        ARR.push(attr2.categoryId + "-" + obj);
      });
    }
  }
  filterValMid3.value = ARR;
  // console.log(111111, filterValMid.value, filterValMid3.value);
  getAttrListFun(); //获取选中分类对应的属性列表-right数据
};

// 3级分类筛选
const changeCate3 = (val, item, index, index2) => {
  // console.log("这是3级分类筛选===", item);
  if (val) {
    //任意选中一个3级分类，默认选中对应的二级分类
    !filterValMid.value.includes(item.categoryId) && filterValMid.value.push(item.categoryId);
  }

  let ARR = [];
  for (let attr2 of selectedLeftObj.value.children) {
    console.log("ppppp", attr2);
    if (attr2.select3 && attr2.select3?.length > 0) {
      attr2.select3.map(obj => {
        ARR.push(attr2.categoryId + "-" + obj);
      });
    }
  }
  filterValMid3.value = ARR;
  // console.log(22222222222, filterValMid.value, filterValMid3.value);
  getAttrListFun(); //获取选中分类对应的属性列表-right数据
};

const getAttrListFun = () => {
  //这里请求接口 获取筛选属性

  // 重新组装二级、三级分类ids
  const attrIds2 = filterValMid.value.flat(); //选中的二级属性ids
  for (let ids2 of attrIds2) {
    const str = filterValMid3.value.find(item => typeof item === "string" && item.includes(ids2));
    !str && filterValMid3.value.push(ids2);
  }

  getWarnStatsList({
    ...props.params,
    categoryIds: filterValMid3.value
  }).then(res => {
    if (res.code === 200) {
      // console.log("查询出来的属性列表===", res);
      _filterData.value = res.data;
    }
  });
};

// ==========================================right==========================================================================================
const resetAll = () => {
  // _category.value = JSON.parse(JSON.stringify(_categoryCopy.value));
  filterValMid.value = [];
  filterValMid3.value = [];
  selectedLeftObj.value = { children: [] };

  _filterData.value = [];
  filterVal.value = [];
  filterVal3.value = [];
  brandIds.value = [];
};
const reset = () => {
  filterVal.value = [];
  filterVal3.value = [];
  brandIds.value = [];
};

//2级属性筛选
const changeAttr2 = (val, item, item2, index) => {
  // console.log('这是2级属性筛选===', item.children, filterVal.value)

  //二级选中的属性id重新排序，按照接口返回的属性顺序排
  let sortArr = [];
  filterVal.value.map((arr, i) => {
    if (index === i) {
      let Arr = [];
      if (arr) {
        for (let ids of arr) {
          const _index = item.children.findIndex(child => child.stastsId == ids);
          if (_index >= 0) {
            Arr[_index] = ids;
          }
        }
      }
      sortArr[index] = Arr;
    }
  });
  filterVal.value[index] = sortArr[index];

  if (!val) {
    item2.select3 = [];
  }

  let ARR = [];
  for (let attr1 of _filterData.value) {
    for (let attr2 of attr1.children) {
      if (attr2.select3 && attr2.select3?.length > 0) {
        attr2.select3.map(obj => {
          ARR.push(attr2.stastsId + "-" + obj);
        });
      }
    }
  }
  filterVal3.value = ARR;
};

// 3级属性筛选
const changeAttr3 = (val, item, item2, index, index2) => {
  // console.log("这是3级属性筛选===", item2);
  if (val) {
    //任意选中一个3级属性，默认选中对应的二级属性
    console.log(9090909090, filterVal.value, index, index2);
    filterVal.value[index] = filterVal.value[index] || [];
    filterVal.value[index][index2] = item2.stastsId;
  }

  let ARR = [];
  for (let attr1 of _filterData.value) {
    for (let attr2 of attr1.children) {
      if (attr2.select3 && attr2.select3?.length > 0) {
        attr2.select3.map(obj => {
          ARR.push(attr2.stastsId + "-" + obj);
        });
      }
    }
  }
  filterVal3.value = ARR;
};

const cancelClick = () => {
  resetAll();
  _isOpen.value = false;
  emit("changeAttr", {
    filterValMid3: filterValMid3.value,
    filterVal: filterVal.value,
    filterVal3: filterVal3.value,
    brandIds: brandIds.value
  });
};
const confirmClick = () => {
  // console.log("抽屉选中的分类id===", filterValMid3.value);
  // console.log("抽屉选中的属性id2222222222===", filterVal.value);
  // console.log("抽屉选中的属性id3333333333===", filterVal3.value);
  _isOpen.value = false;
  emit("changeAttr", {
    filterValMid3: filterValMid3.value,
    filterVal: filterVal.value,
    filterVal3: filterVal3.value,
    brandIds: brandIds.value
  });
};

defineExpose({ reset, resetAll });
</script>

<style lang="scss">
h4 {
  margin: 0;
  padding: 0;
}
.my-drawer {
  .el-drawer {
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }
  .el-drawer__header {
    font-size: 18px;
    color: #131414;
    margin-bottom: 0px;
    padding-bottom: 16px;
    border: 1px solid #d8d8d8;
    h4 {
      font-weight: normal;
      position: relative;
      padding-left: 14px;
      &::before {
        position: absolute;
        content: "";
        left: 0;
        top: 6px;
        width: 6px;
        height: 6px;
        background-color: #409eff;
        border-radius: 50%;
      }
    }
  }
  .el-drawer__body {
    padding: 0;
  }
  .el-drawer__footer {
    text-align: center !important;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 14px 20px;
  }
}
</style>
<style lang="scss" scoped>
@import "@/assets/styles/index";
p,
h1 {
  margin: 0;
  padding: 0;
  font-weight: normal;
}

:deep(.el-collapse-item__header) {
  font-size: 16px;
  color: #3d3d3d;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;

  .attr-wrap,
  .cate-wrap {
    display: flex;
    align-items: center;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    height: 32px;
    padding: 0 8px;
    margin-bottom: 4px;
    color: #3d3d3d;
    background-color: white;

    .cate3,
    .attr2,
    .attr3 {
      color: #3d3d3d;
      font-size: 12px;
    }
    &:not(:last-of-type) {
      margin-right: 8px;
    }
  }
}

:deep(.el-checkbox.el-checkbox--small.is-bordered) {
  height: auto;
  height: 32px;

  .el-checkbox__label {
    .attr-wrap,
    .cate-wrap {
      display: flex;
      align-items: center;
    }
  }
}

.content {
  display: flex;
  .left {
    flex: 1;
    height: calc(100vh - 120px);
    ul {
      list-style-type: none;
      padding: 0;
      margin: 0;
      li {
        padding: 16px 20px;
        font-size: 14px;
        color: #3d3d3d;
        cursor: default;
        &.active {
          background-color: #f5f7fa;
        }
      }
    }
  }
  .middle {
    width: 398px;
    height: calc(100vh - 120px);
    background-color: #f5f7fa;
    border-right: 1px solid #d8d8d8;
    .middle-list-item {
      padding: 20px 20px 0 20px;
      .title {
        font-size: 14px;
        color: #3d3d3d;
        margin-bottom: 10px;
      }
    }
  }
  .right {
    width: 398px;
    height: calc(100vh - 120px);
  }
}

.attr-item {
  padding: 10px 20px 0px 20px;
  & > p {
    min-width: 60px;
    color: #86909c;
    font-size: 14px;
    margin-bottom: 10px;
  }
}
</style>
